var utils = require('../../../utils/utils.js'),
appData = getApp().globalData,
app = getApp(),
ex = 0;
Page({
  data: {
    hasHidden: true,
    inputCode: '',
    info: [
      { id: "0", icon: "scan", name: "扫码", info: "校验顾客优惠券" },
      { id: "1", icon: "input", name: "输入", info: "手动输入优惠券编码" },
      { id: "2", icon: "record", name: "优惠券兑换记录", info: "我处理的优惠券兑换记录" },
      { id: "3", icon: "record", name: "赏金兑换记录", info: "我处理的赏金兑换记录" }
    ]
  },
  tap: function (e) {
    var that = this;
    switch (e.currentTarget.id) {
      case "0": 
        wx.scanCode({
          onlyFromCamera: true,
          success(res) {
            console.log('result', res.result);
            that.simpleCheck(res.result);            
          },
        })
      break;
      case "1":
        this.setData({ hasHidden: !this.data.hasHidden });
        console.log(e)
      break;
      case "2":
        wx.navigateTo({ url: '../record/record?path=record' })
      break;
      case "3":
        wx.navigateTo({ url: '../record/record?path=record_money' })
      break;
    }
  },

  simpleCheck: function (code) {
    if (code.length < 16){
      app.toast('无效优惠券1');
      return 0;
    }
    ex = 0;
    var t = code.substring(13), line = 1, char = 1;
    for (let i = 0; i < t.length; i++) {
      var c = t[i];
      if (c == '%') {
        line--;
      } else if (c == '$') { 
        line--, ex ++;
      } else if (!(c >= '0' && c <= '9' || c >= 'a' && c <= 'f')) {
        app.toast('无效优惠券2');
        return 0;
      }
    }
    if (line) {
      console.log('line:', line)
      app.toast('无效优惠券3');
      return 0;
    } else {
      this.checkQRcode(code);
    } 
  },

  checkQRcode: function(code){
    // console.warn(code)
    // console.warn(parseInt('5c' + code.substring(0, 6), 16))
    // console.warn(code.substring(6, 17))
    // console.warn(parseInt(code.substring(17).split('%')[0], 16))
    // console.warn(code.substring(17).split('%')[1])
    // console.warn((new Date().getTime()/1000))
    var that = this, 
    spChar = ex ? '$' : '%', 
    rect = parseInt('5' + code.substring(3, 10), 16),
    CK_data = {
      ticketid: parseInt(code.substring(13).split(spChar)[0], 16),
      id: code.substring(13).split(spChar)[1],
    };
    app.request('admin/check', CK_data, '校验中').then((info) => {
      console.log(info.name, info.data)
      var u = info.data.user, 
      o = info.data.owner,
      r = info.data.receive,
      s = info.data.share,
      x = info.data.exchange;
      if (spChar == '%') {
        if (!u || !o || !s || !r) {
          app.toast('无效优惠券');
          return 0;
        } 
        var giv = o.openid + o.openid,
        rec = u.openid + u.openid,
        key = 
          giv.substring(rect % 28, rect % 28 + 3) +
          rect.toString(16).substring(1) +
          rec.substring(rect % 28 + 3, rect % 28 + 6);

        if (key == code.substring(0, 13)) {
          if (r.validity != '0') {
            app.modal('校验成功',
              '请核对顾客信息\n' +
              '\n优惠金额：' + r.total + '元' +
              '\n顾客姓名：' + u.name +
              '\n手机号码：' + u.phone,
              '取消', '核实正确',
              '', '#f00'
            ).then ((res) => { that.exchange(s, r); }
            ).catch((res) => { app.toast('优惠券未使用'); }
            )
          } else app.modal('优惠券已使用',
            '此优惠券已被使用。\n' +
            '\n优惠金额：' + info.data.receive.total + '元' +
            '\n顾客姓名：' + u.name +
            '\n手机号码：' + u.phone +
            '\n使用时间：' + info.data.receive.ex_date,
          )
        } else {
          console.log(code.substring(0, 13), key)
          app.modal('校验失败', '此优惠券可能是伪造券。' )
        }
      } else {      /* 赏金兑换 */
        if (!u || !x || !r) {
          app.toast('无效优惠券');
          return 0;
        } 
        var giv = u.openid + u.openid,
        key = 
          giv.substring(rect % 28, rect % 28 + 3) +
          rect.toString(16).substring(1) +
          giv.substring(rect % 28 + 3, rect % 28 + 6);

        if (key == code.substring(0, 13)) {
          if (x.validity != '0') {
            app.modal('赏金兑换校验成功',
              '请核对顾客信息\n' +
              '\n赏金金额：' + x.total + '元' +
              '\n顾客姓名：' + u.name +
              '\n手机号码：' + u.phone,
              '取消', '核实正确',
              '', '#e6b54b'
            ).then ((res) => { that.money(x); }
            ).catch((res) => { app.toast('优惠券未使用'); }
            )
          } else app.modal('赏金券已使用',
            '此优惠券已被使用。\n' +
            '\n优惠金额：' + x.total + '元' +
            '\n顾客姓名：' + u.name +
            '\n手机号码：' + u.phone +
            '\n使用时间：' + x.update_time,
          )
        } else {
          console.log(code.substring(0, 13), key)
          app.modal('校验失败', '优惠券与用户不匹配。' )
        }
      }
    })
    
  },

  exchange: function(share, receive) {
    var total = share.total == null ? 
      parseInt(receive.total) : 
      parseInt(share.total) + parseInt(receive.total),
    EX_data = {
      admin: this.data.admin.name,
      id: share.share_id,
      recid: receive.id,
      total: total,
      inv_num: parseInt(share.inv_num) + 1,
      time: utils.formatDate(new Date().getTime() , 'datetime'),
    };
    app.request( 'admin/exchange', EX_data, '上传中').then((res) => {
      app.modal( '上传完成',
        '优惠券兑换成功！\n' +
        '\n折抵金额:' + EX_data.total + '元' +
        '\n处理人员：' + EX_data.admin +
        '\n' + EX_data.time,
        '', '完成'
      )
    })
  },

  money: function(x) {
    var EX_data = {
      admin: this.data.admin.name,
      id: x.share_id,
      owner: x.owner,
      time: utils.formatDate(new Date().getTime(), 'datetime'),
    };
    app.request('admin/exchange_money', EX_data, '上传中').then((res) => {
      app.modal('上传完成',
        '赏金券兑换成功！\n' +
        '\n折抵金额:' + x.total + '元' +
        '\n处理人员：' + EX_data.admin +
        '\n' + EX_data.time,
        '', '完成'
      )
    })
  },

  open: function (e) { this.setData({ hasHidden: !this.data.hasHidden }) },
  inp:  function (e) { this.setData({ inputCode : e.detail.value }) },
  finish: function() { this.simpleCheck( this.data.inputCode) },
  cancel: function() { this.setData({ hasHidden: true, inputCode: '' }) },
  onLoad: function() { this.setData({ admin: appData.admin }) },

})